package net.thxjj.mobileServer.controller.mobile;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.thxjj.mobileServer.controller.base.BaseController;
import net.thxjj.mobileServer.entity.*;
import net.thxjj.mobileServer.mongodao.MongoDevLogDao;
import net.thxjj.mobileServer.service.IGenieService;
import net.thxjj.mobileServer.service.IUserService;
import net.thxjj.mobileServer.util.Tools;
import net.thxjj.mobileServer.util.sampleUtil.NonBlockingPublisher;
import net.thxjj.mobileServer.websocket.WebsocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName:EchoController
 * @Description:TODO
 * @Autor:TracyHenry
 * @Date:2022/12/18 0018
 * @Version:1.0
 **/
@Slf4j
@Controller
@RequestMapping("/alexa")
public class EchoController extends BaseController {

    private static final String REDICT_URI= "REDICT_URI";
    private static final String CLIENT_ID= "CLIENT_ID";
    private static final String STATUS= "STATUS";
    private static final String RESPONSE_TYPE= "RESPONSE_TYPE";
    private static long msgId = 0;

    @Autowired
    private IGenieService iGenieService;


    @Autowired
    private MongoDevLogDao mongoDevLogDao;


    /**
     * 登录页面授权
     * @return
     */
    @RequestMapping(value="/tologin",method= RequestMethod.GET)
    public Object tologin() {

        String pamaramp = this.getParameterMap().toString();

        log.info("获取到的参数:"+pamaramp);

        String redict_uri = this.getParameterMap().getString("redirect_uri");
        String state = this.getParameterMap().getString("state");
        String response_type = this.getParameterMap().getString("response_type");
        String client_id = this.getParameterMap().getString("client_id");
        this.getSession().setMaxInactiveInterval(1800);
        this.getSession().setAttribute(REDICT_URI,redict_uri);
        this.getSession().setAttribute(CLIENT_ID,client_id);
        this.getSession().setAttribute(STATUS,state);
        this.getSession().setAttribute(RESPONSE_TYPE,response_type);


        return "page/loginAlexa";

    }

    /**
     * login
     * @return
     * h5授权登录接口
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Object login(){

        String redict_uri = (String)this.getSession().getAttribute(REDICT_URI);
        log.info("亚马逊redict_uri:"+redict_uri);
        String client_id = (String)this.getSession().getAttribute(CLIENT_ID);
        String state = (String)this.getSession().getAttribute(STATUS);
        String response_type = (String)this.getSession().getAttribute(RESPONSE_TYPE);

        if(Tools.isEmpty(redict_uri)||Tools.isEmpty(client_id)||Tools.isEmpty(state)||Tools.isEmpty(response_type)){
            return ResponseModel.getModel(GenieErrcode.PARAMETER_EMPTY,null);
        }

        if(!EchoResum.CLINET_ID.equals(client_id)){
            return ResponseModel.getModel(GenieErrcode.CLIENT_ID_NOT_CORRECT,null);
        }

        if(!"code".equals(response_type)){
            return ResponseModel.getModel(GenieErrcode.PARAMETER_ERROR,null);
        }

        String username = this.getParameterMap().getString("username");
        String password = this.getParameterMap().getString("password");

        return iGenieService.loginOauthEcho(username,password,redict_uri,state);
    }


    /**
     * 供天猫精灵获取access_token和refresh_token
     * @return
     */
    @RequestMapping(value="/token",method= RequestMethod.POST)
    @ResponseBody
    public Object token()  {
        String pamaramp = this.getParameterMap().toString();
        log.info("获取到的参数2:"+pamaramp);
        String grant_type = this.getParameterMap().getString("grant_type");
        String client_id = this.getParameterMap().getString("client_id");


        if(Tools.isEmpty(grant_type)||Tools.isEmpty(client_id)){
            log.info("grant_type｜client_id为空");
            return ResponseModel.getGenieErrorCode(GenieErrcode.PARAMETER_EMPTY);
        }

        if(!EchoResum.CLINET_ID.equals(client_id)){
            log.info("CLIENT_ID错误");
            return ResponseModel.getGenieErrorCode(GenieErrcode.CLIENT_ID_NOT_CORRECT);
        }

        if(!"authorization_code".equals(grant_type)&&!"refresh_token".equals(grant_type)){
            log.info("参数错误");
            return ResponseModel.getGenieErrorCode(GenieErrcode.PARAMETER_ERROR);
        }

        String code = this.getParameterMap().getString("code");
        String refresh_token = this.getParameterMap().getString("refresh_token");

        if("authorization_code".equals(grant_type)&&Tools.isEmpty(code)){
            log.info("code为空");
            return ResponseModel.getGenieErrorCode(GenieErrcode.PARAMETER_EMPTY);
        }

        if("refresh_token".equals(grant_type)&&Tools.isEmpty(refresh_token)){
            log.info("refresh_token为空");
            return ResponseModel.getGenieErrorCode(GenieErrcode.PARAMETER_EMPTY);
        }

        GenieOauthBean genieOauthBean;
        if("authorization_code".equals(grant_type)){
            genieOauthBean = iGenieService.getGenieOauthBeanCode(code,null);
        }else {
            genieOauthBean = iGenieService.getGenieOauthBeanCode(null,refresh_token);
        }

        if(genieOauthBean==null){
            log.info("genieOauthBean 不存在");
            return ResponseModel.getGenieErrorCode(GenieErrcode.CODE_IS_NOT_EXIST);
        }

        long login_time = genieOauthBean.getLoginTime();

        long cur_time = System.currentTimeMillis();


        if(cur_time>(login_time+GenieResum.REFRESH_TOKEN_EXPIRED_SECOND)){
            log.info("REFRESH_TOKEN 过期");
            return ResponseModel.getGenieErrorCode(GenieErrcode.REFRESH_TOKEN_IS_EXSPIRED);
        }




        HashMap<String,Object> reslut = iGenieService.updateAccessToken(grant_type,genieOauthBean);

        log.info("最终获取到的token信息:"+reslut);

        return reslut;

    }


    /**
     * alexa 远程控制
     * @return
     */
    @RequestMapping(value="/control",method= RequestMethod.POST)
    @ResponseBody
    public Object control(@RequestBody JSONObject jsonObject)  {

        log.info("插座控制:"+jsonObject.toJSONString());



        String token = this.getRequest().getHeader("Authorization");
        log.info("获取到的Token3:"+token);
        GenieOauthBean genieOauthBean = iGenieService.getGenieOauthBean(token);
        if(genieOauthBean==null || System.currentTimeMillis()>(genieOauthBean.getRefreshTime()+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND)){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

          String deviceTotal = jsonObject.getString("deviceId");
        String state = jsonObject.getString("state");
        if(Tools.isEmpty(deviceTotal)||deviceTotal.contains("-")){
            return ResponseEntity.status(400).build();
        }

        if(Tools.isEmpty(state)){
            return ResponseEntity.status(400).build();
        }

        if(!"ON".equals(state)&&!"OFF".equals(state)){
            return ResponseEntity.status(400).build();
        }

        long index = deviceTotal.indexOf("_");
        String device_gateway = deviceTotal.substring(0, (int) index);
        String device_address = deviceTotal.substring((int) (index+1));



        msgId++;
        if(msgId==256){
            msgId = 0;
        }

        String content = String.format("{\"hw_id\":\"%s\",\"msg\":{\"CMD_CODE\":1,\"str1\":\"%s000603\",\"str2\":\"01%02x%s\",\"str3\":\"\"},\"msg_id\":13,\"namespace\":\"config\",\"source\":\"app\",\"target\":\"gateway\"}",device_gateway,device_address,msgId,"ON".equals(state)?"01":"00");
        log.info("插座命令:"+content);
        DataBean dataBean = JSONObject.parseObject(content,DataBean.class);

        Thread blockingPublishThread = new Thread(new NonBlockingPublisher(WebsocketServer.awsIotClient,dataBean));
        blockingPublishThread.start();

        HashMap<String,Object> resp = new HashMap<>();
         resp.put("code",200);
        return resp;

    }

    /**
     * alexa获取插座列表
     */
    @RequestMapping(value = "/deviceList",method = RequestMethod.GET)
    @ResponseBody
    public Object deviceList(){

        String token = this.getRequest().getHeader("Authorization");
        log.info("获取到的Token:"+token);
        GenieOauthBean genieOauthBean = iGenieService.getGenieOauthBean(token);
        if(genieOauthBean==null || System.currentTimeMillis()>(genieOauthBean.getRefreshTime()+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND)){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }


        String pamaramp = this.getParameterMap().toString();
        log.info("挖掘设备:"+pamaramp);

     HashMap<String,String> map = new HashMap<String,String>();
     map.put("deviceId","000c2933eaa6_6C0B");
     map.put("name","window");
        List<HashMap<String,String>> list = new ArrayList<>();
        list.add(map);
        return  list;

    }

    /**
     * alexa获取单个插座状态
     */
    @RequestMapping(value = "/deviceResportState",method = RequestMethod.GET)
    @ResponseBody
    public Object deviceResportState(){

        String token = this.getRequest().getHeader("Authorization");
        log.info("获取到的Token2:"+token);
        GenieOauthBean genieOauthBean = iGenieService.getGenieOauthBean(token);
        if(genieOauthBean==null || System.currentTimeMillis()>(genieOauthBean.getRefreshTime()+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND)){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        String deviceTotal = this.getParameterMap().getString("deviceId");
        log.info("获取到的参数deviceTotal:"+this.getParameterMap().toString());
        if(Tools.isEmpty(deviceTotal)||deviceTotal.contains("-")){
            return ResponseEntity.status(400).build();
        }

        long index = deviceTotal.indexOf("_");

        String device_gateway = deviceTotal.substring(0, (int) index);
        String device_address = deviceTotal.substring((int) (index+1));
        long address = Long.parseLong(device_address,16);
        DevLog deviceLog = mongoDevLogDao.getDevShadow(device_gateway,address,"0006");


        DataBean dataBean = JSONObject.parseObject(deviceLog.getContent(),DataBean.class);
        if(dataBean!=null&& !Tools.isEmpty(dataBean.getMsg().getStr2())){
            if(dataBean.getMsg().getStr2().length()>=14){
                String status = dataBean.getMsg().getStr2().substring(12,14);

                HashMap<String,Object> map = new HashMap<>();
                map.put("isOpen","01".equals(status)?1:0);
                return  map;
            }else{
                return ResponseEntity.status(400).build();
            }

        }else{
            return ResponseEntity.status(400).build();
        }



    }


}